package com.tnsw.facebookautoliker.helper.command;

import java.nio.BufferUnderflowException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.os.Bundle;

import com.facebook.HttpMethod;
import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Settings;
import com.facebook.model.GraphUser;
import com.tnsw.coreutils.MyLog;
import com.tnsw.coreutils.database.RecordBase;
import com.tnsw.facebookautoliker.database.DBManager;
import com.tnsw.facebookautoliker.database.FriendsList;
import com.tnsw.facebookautoliker.helper.FacebookCommandObject;
import com.tnsw.facebookautoliker.helper.GeneralManager;
import com.tnsw.facebookautoliker.services.AutoLikerService;

public class GetFriendsList extends FacebookCommandObject implements Request.Callback, Runnable {

	private DBManager dbm;
	private GeneralManager gm;
	private Response getFriendsListResponse;
	private boolean bGetPhoto = true;
	
	public GetFriendsList(Context context, boolean bGetPhoto) {
		super(context);
		this.bGetPhoto = bGetPhoto;
		this.tag = "GetFriendsList";
		this.gm = GeneralManager.getInstance();
		this.dbm = DBManager.getInstance(context);
	}

	@Override
	protected void handleResult(Response response) {
		super.handleResult(response);
		
		this.getFriendsListResponse = response;
		if (response != null) {
			Thread t = new Thread(this);
			t.start();	
		}
		
	}
	
	@Override
	public void execute() {
		// URL:	https://graph.facebook.com/me/friends?access_token=ACCESS_TOKEN_REMOVED&format=json&sdk=android&migration_bundle=fbsdk%3A20121026

		super.execute();
		
		if (MyLog.isProduction == false) {
			Settings.addLoggingBehavior(LoggingBehavior.REQUESTS);
		}
		
		Session session = Session.openActiveSessionFromCache(this.context);
		if (session != null) {
			String path = "/me/friends";
			Request req = new Request(session, path, null, HttpMethod.GET);
			Bundle params = new Bundle();
			params.putString("fields", "id,name,gender");
			req.setParameters(params);
			req.setCallback(this);
			this.standardExecute(req);	
		}
	}

	@Override
	public void onCompleted(Response response) {
		this.handleResult(response);
	}

	@Override
	public void run() {
		try {
			JSONObject jo = this.getFriendsListResponse.getGraphObject().getInnerJSONObject();
			JSONArray ja = jo.getJSONArray("data");
			
			int len = ja.length();
			MyLog.d(tag, "json.count=" + len);
			int i;
			int recordCount = 0;
			for (i = 0; i < len; i++) {
				JSONObject jFriend = ja.getJSONObject(i);
				String id = jFriend.getString("id");
				String name = jFriend.getString("name");
				String gender = "";
				if (jFriend.has("gender")) {
					gender = jFriend.getString("gender");
				}
								
				ArrayList<RecordBase> a = this.dbm.getRecords(FriendsList.class.getName(), "select * from friends_list where id=?", new String[] {id}, 0);
				if (a == null) {
					// new friend
					FriendsList fl = new FriendsList();
					fl.primarykey = this.dbm.getNewPrimarykey();
					fl.id = id;
					fl.name = name;
					fl.gender = gender;
					
					long nowl = System.currentTimeMillis();
					fl.created = nowl;
					fl.lastupd = nowl;
					fl.is_friend = "Y";
					
					long result = this.dbm.insertRecord("friends_list", fl, null, true);
					if (result != -1l) {
						recordCount += 1;
					}
					
				} else {
					// existing friend, may have update..
					FriendsList fl = (FriendsList) a.get(0);
					fl.id = id;
					fl.name = name;
					fl.gender = gender;
					int recordAffected = this.dbm.updateRecordByPrimarykey("friends_list", fl, true);
					AutoLikerService aService = AutoLikerService.getInstance();
					aService.updateFriendsList(fl.id, fl);
					recordCount += recordAffected;
				}
			}
			
			MyLog.d(tag, "recordCount=" + recordCount);
			this.fbm.updateCommandStatus(this, 200, null);
			
			if (this.bGetPhoto) {
				RefreshFriendsList a1 = new RefreshFriendsList(context, recordCount);
				a1.setApplyCounter(false);
				gm.addNewQueue(a1, 2);

				for (i = 0; i < recordCount; i++) {
					JSONObject jFriend = ja.getJSONObject(i);
					String id = jFriend.getString("id");
					String name = jFriend.getString("name");
					
					GetPhoto gp = new GetPhoto(this.context, id, name);
					gp.setParent(a1);
					this.gm.addNewQueue(gp, 2);
				}	
			}
			
			
			
		} catch (Exception e) {
			MyLog.e(tag, "handleResult - " + e.toString(), e);
		}		
	}

}